package com.xhq.tools.rsa;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;

/**
 * @author huiny
 * @since 2021/8/14 23:51
 */
public class RsaSign {
    private static final String DEFAULT_SHA = "SHA256WithRSA";

    public static String sign(String content, String privateKey)
            throws NoSuchAlgorithmException, InvalidKeySpecException,
            InvalidKeyException, UnsupportedEncodingException, SignatureException {
        return sign(content, privateKey, null);
    }

    public static String sign(String content, String privateKeyDerString, String encode)
            throws NoSuchAlgorithmException, InvalidKeySpecException,
            InvalidKeyException, UnsupportedEncodingException, SignatureException {
        var privateKey = RsaKeyHelper.getPrivateKeyFromDerString(privateKeyDerString);

        // SHA1WithRSA, SHA256WithRSA, SHA512WithRSA
        java.security.Signature signature = java.security.Signature.getInstance(DEFAULT_SHA);
        signature.initSign(privateKey);
        signature.update((encode == null) ? content.getBytes() : content.getBytes(encode));
        byte[] signed = signature.sign();
        return Base64Helper.encode(signed);
    }

    public static boolean verify(String content, String sign, String publicKey)
            throws NoSuchAlgorithmException, InvalidKeySpecException,
            InvalidKeyException, UnsupportedEncodingException, SignatureException {
        return verify(content, sign, publicKey, null);
    }

    public static boolean verify(String content, String sign, String publicKeyBase64String, String encode)
            throws NoSuchAlgorithmException, InvalidKeySpecException,
            InvalidKeyException, UnsupportedEncodingException, SignatureException {
        var publicKey = RsaKeyHelper.getPublicKeyFromBase64String(publicKeyBase64String);
        java.security.Signature signature = java.security.Signature.getInstance(DEFAULT_SHA);
        signature.initVerify(publicKey);
        signature.update(encode == null ? content.getBytes() : content.getBytes(encode));
        return signature.verify(Base64Helper.decode(sign));
    }
}
